<?php

class DatabaseObject_Orders extends DatabaseObject {

    public $shop = null;
    public $user = null;
    public $product = null;
    public $count = null;
    // public $currency = null;
    public $priceproduct = null;

    public function __construct($db) {
        parent::__construct($db, 'orders', 'id');

        // далее перечислены все поля таблицы

        $this->add('userId');
        $this->add('shopId');
        $this->add('price');
        $this->add('status');
        $this->add('date');
        $this->add('city');
        $this->add('zipcode');
        $this->add('address');
        $this->add('fio');
        $this->add('phone');
        $this->add('pc');
        $this->add('pc2');
        $this->add('currency');
    }

    protected function postLoad() {
        parent::postLoad();

        // загрузим прикрпленные файлы
        $user = new DatabaseObject_User($this->getDb());
        $shop = new DatabaseObject_User($this->getDb());
        $product = new DatabaseObject_Products($this->getDb());
        $user->load($this->userId);
        $shop->load($this->shopId);
        $id = $this->getId();
        $prod = $this->getDb()->fetchAll("SELECT * FROM `order_products` WHERE orderId='$id'");
        foreach ($prod as $key => $value) {
            $product->load($value['product_id']);
            $products[] = $product;
            $count[] = $value['count'];
            $priceproduct[] = $product->price * $value['count'];
        }

        $this->user = $user;
        $this->shop = $shop;
        $this->product = $products;
        $this->count = $count;
        $this->price = CustomControllerAction::currency($this->price, $this->currency, DatabaseObject_User::GetCurrencyUser($this->getDb(), Zend_Auth::getInstance()->getIdentity()->id)) * $value['count'];
        $this->priceproduct = $priceproduct;

        return true;
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создание запроса на получение
        $select = $db->select();
        $select->from(array('or' => 'orders'), array());

        return $select;
    }

    public static function GetBasket($db, $options = array(), $type = false) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'or.id'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'or.*');
        if ($type)
            $select->where("status = '" . $type . "'");
        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if ($options['where'] != '')
            $select->where($options['where']);

        $select->order($options['order']);

        // получим данные из базы
        $data = $db->fetchAll($select);

        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);
        $cat_ids = array_keys($cats);

        if (count($cat_ids) > 0)
            foreach ($cats as $key => $value) {
                $user = new DatabaseObject_User($db);

                $user->load($value->userId);
                $shop = new DatabaseObject_User($db);

                $shop->load($value->shopId);

                $value->user = $user;
                $value->shop = $shop;
            }
        if (count($cat_ids) == 0)
            return array();

        return $cats;
    }

    public static function GetCount($db, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        if ($type)
            $select->where('status = ?', $type);
        return $db->fetchOne($select);
    }

    // получение количество продаж
    public static function GetShopCount($db, $shopId, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        if ($type)
            $select->where('status = ?', $type);
        $select->where('shopId = ?', $shopId);
        return $db->fetchOne($select);
    }

    /// количество продаж
    public static function GetUserCount($db, $userId, $type = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        if ($type)
            $select->where('status = ?', $type);
        $select->where('userId = ?', $userId);
        return $db->fetchOne($select);
    }

    // список продуктов
    public static function GetBasketProducts($db, $options = array()) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'or.id'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        $query = "SELECT distinct product_id FROM `orders_products`";
        if ($options['where'])
            $query = "WHERE $options[where]";
        if ($options['limit'])
            $query = "LIMIT $options[limit]";

        $data = $db->query($query);
        if (count($data) > 0)
            foreach ($data as $key => $value) {
                $user = new DatabaseObject_User($db);
                $shop = new DatabaseObject_User($db);

                $user->load($value->userId);
                $shop->load($value->shopId);

                $value->user = $user;
                $value->shop = $shop;
            }
    }

    //////// Получение суммы всех сделок    
    public static function GetSumPrice($db) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'sum(price*(SELECT value FROM currency WHERE currency.id = currency))');

        return $db->fetchOne($select);
    }

    //////// Получение количество проданных товаров    
    public static function GetCountAllProduct($db) {
        return $query = $db->fetchOne("SELECT count(*) FROM order_products");

        // return $db->fetchOne($select);
    }

}
